import { useMemo, useState } from "react"
import { Image, ImageStyle, Pressable, TextStyle, View, ViewStyle } from "react-native"
import { router } from "expo-router"

import { Button, Screen, Text } from "@/components"
import { useStores } from "@/models"
import { useAppTheme } from "@/theme/context"
import { $styles } from "@/theme/styles"
import type { ThemedStyle } from "@/theme/types"
import { useHeader } from "@/utils/useHeader"

type TabKey = "works" | "favorites" | "uploads"

interface TabItem {
  id: string
  title: string
  summary: string
  timestamp: string
}

const tabOptions: { key: TabKey; label: string }[] = [
  { key: "works", label: "作品" },
  { key: "favorites", label: "收藏" },
  { key: "uploads", label: "上传" },
]

export default function MePage() {
  const { themed, theme } = useAppTheme()
  const { userStore } = useStores()
  useHeader(
    {
      title: "我的",
      titleMode: "center",
      rightIcon: "settings",
      onRightPress: () => {
        if (__DEV__) {
          console.log("Navigate to settings")
        }
        router.push("/settings")
      },
    },
    [],
  )

  const [activeTab, setActiveTab] = useState<TabKey>("works")

  const tabData = useMemo<Record<TabKey, TabItem[]>>(
    () => ({
      works: [
        {
          id: "work-1",
          title: "浮空城日落",
          summary: "吉卜力风格场景概念图，结合柔和光影与漂浮岛屿。",
          timestamp: "2 小时前",
        },
      ],
      favorites: [],
      uploads: [],
    }),
    [],
  )

  const toPay = () => {
    router.push("/payModal")
  }

  const currentItems = tabData[activeTab]

  return (
    <Screen preset="scroll" style={themed($screen)} contentContainerStyle={themed($content)}>
      <View style={themed($profileSection)}>
        <Image
          source={{
            uri: "https://images.unsplash.com/photo-1494790108377-be9c29b29330?auto=format&fit=crop&w=200&q=80",
          }}
          style={themed($avatar)}
        />

        <View style={$styles.flex1}>
          <Text weight="medium" size="lg" text="Apex" />
          <View style={[$styles.row, $styles.alignCentered]}>
            <Text size="xs" style={themed($profileSubtitle)}>
              余额 · {userStore.profile.wallet?.totalCoin}
            </Text>
            <Button
              onPress={toPay}
              style={{
                paddingVertical: 4,
                minHeight: 20,
                marginLeft: 12,
              }}
              text={"充值"}
            ></Button>
          </View>
        </View>
      </View>

      <View style={themed($tabsRow)}>
        {tabOptions.map((tab) => {
          const isActive = tab.key === activeTab
          return (
            <Pressable
              key={tab.key}
              onPress={() => setActiveTab(tab.key)}
              style={[
                themed($tabChip),
                isActive && themed($tabChipActive),
                {
                  marginRight: tab.key !== "uploads" ? theme.spacing.sm : 0,
                },
              ]}
              accessibilityRole="button"
            >
              <Text
                weight={isActive ? "medium" : "normal"}
                size="sm"
                style={themed(isActive ? $tabChipTextActive : $tabChipText)}
                text={tab.label}
              />
            </Pressable>
          )
        })}
      </View>

      <View style={themed($listContainer)}>
        {currentItems.length > 0 ? (
          currentItems.map((item) => (
            <View key={item.id} style={themed($noteCard)}>
              <Text weight="medium" size="md" text={item.title} />
              <Text size="xs" style={themed($noteSummary)} text={item.summary} />
              <Text size="xxs" style={themed($noteTimestamp)} text={item.timestamp} />
            </View>
          ))
        ) : (
          <View style={themed($emptyState)}>
            <Text size="sm" style={themed($emptyStateText)} text="去创作" />
          </View>
        )}
      </View>
    </Screen>
  )
}

const $screen: ThemedStyle<ViewStyle> = ({ colors }) => ({
  flex: 1,
  backgroundColor: colors.background,
})

const $content: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  flexGrow: 1,
  paddingHorizontal: spacing.lg,
  paddingTop: spacing.lg,
  paddingBottom: spacing.xxl,
})

const $profileSection: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  flexDirection: "row",
  alignItems: "center",
  marginBottom: spacing.lg,
})

const $avatar: ThemedStyle<ImageStyle> = ({ spacing }) => ({
  width: 72,
  height: 72,
  borderRadius: 36,
  marginRight: spacing.md,
  backgroundColor: "#E6E6E6",
})

const $profileSubtitle: ThemedStyle<TextStyle> = ({ colors, spacing }) => ({
  color: colors.textDim,
})

const $tabsRow: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  flexDirection: "row",
  alignItems: "center",
  marginBottom: spacing.md,
})

const $tabChip: ThemedStyle<ViewStyle> = ({ colors, spacing }) => ({
  paddingHorizontal: spacing.md,
  paddingVertical: spacing.xs,
  borderRadius: spacing.lg,
  borderWidth: 1,
  borderColor: colors.separator,
  backgroundColor: colors.palette.neutral100,
})

const $tabChipActive: ThemedStyle<ViewStyle> = ({ colors }) => ({
  backgroundColor: colors.tint,
  borderColor: colors.tint,
})

const $tabChipText: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.text,
})

const $tabChipTextActive: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.palette.neutral100,
})

const $listContainer: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  paddingTop: spacing.xs,
})

const $noteCard: ThemedStyle<ViewStyle> = ({ colors, spacing }) => ({
  backgroundColor: colors.palette.neutral100,
  borderRadius: spacing.md,
  padding: spacing.md,
  borderWidth: 1,
  borderColor: colors.separator,
  marginBottom: spacing.sm,
})

const $noteSummary: ThemedStyle<TextStyle> = ({ colors, spacing }) => ({
  color: colors.textDim,
  marginTop: spacing.xs,
  marginBottom: spacing.xs,
})

const $noteTimestamp: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.textDim,
})

const $emptyState: ThemedStyle<ViewStyle> = ({ colors, spacing }) => ({
  borderWidth: 1,
  borderColor: colors.separator,
  borderStyle: "dashed",
  borderRadius: spacing.md,
  paddingVertical: spacing.xl,
  alignItems: "center",
  marginTop: spacing.sm,
})

const $emptyStateText: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.textDim,
})
